package com.qin.controller;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.Shopping;
import com.qin.entity.User;
import com.qin.service.ShoppingService;
import com.qin.service.impl.ShoppingServiceImpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;

/**
 * 删除购物车的几率
 */
@WebServlet("/shopping/*")
public class DeleteShoppingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ShoppingService shoppingService = new ShoppingServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doDelete(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doDelete(request, response);
	}
	
	@Override
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 拿到要删除记录的id（可能是多个）
		// 先拿到请求路径上的id
		// 拿到请求的url地址,和请求content路径
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();

		// 去掉*/shopping/前缀
		String replace = requestURI.replace(contextPath + "/shopping/", "");
		StaticLog.debug("要删除的购物车记录是：{}（他的图书id）", replace);

		// 拿到用户id
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
			
		// 得到当前user的购物车记录
		List<Shopping> shoppingItemsByUserId = shoppingService.getShoppingItemsByUserId(user.getId());
		if(!StrUtil.isEmpty(replace)) {
			// 拿到要删除记录的图书分类的id
			long bookId = Long.parseLong(replace);
			
			// 遍历删除对应的图书分类的id
			shoppingItemsByUserId.stream().forEach(shopping->{
				if(shopping.getBookId() == bookId) {
					// 删除这条记录
					shoppingService.logicDeleteShopping(shopping.getId());
				}
			});
			
		}else {
			// 尝试从请求域中获取id数组
			String bookStrIds = request.getParameter("bookIds");
			// 把string转成JSON数组，再转成set
			JSONArray parseArray = JSONUtil.parseArray(bookStrIds);
			Set<Long> collect = JSONUtil.toList(parseArray, Long.class).stream().collect(Collectors.toSet());
			
			StaticLog.debug("要删除的id有：{}", collect);
			
			// 拿到了就遍历这个数组
			if(collect != null && collect.size() > 0) {
				
				// 遍历删除对应的图书分类的id
				shoppingItemsByUserId.stream().forEach(shopping->{
					// 如果包含的话
					if(collect.contains(shopping.getBookId())) {
						// 删除这条记录
						shoppingService.logicDeleteShopping(shopping.getId());
					}
				});
			}
		}
		
		// 最后，重定向到当前页
		response.sendRedirect(contextPath+"/shoppingcart");
			
			
	}

}
